package com.home.security.browser.auth.service;

import com.home.common.constants.Constants;
import com.home.common.constants.i18n.I18nMessages;
import com.home.common.enums.OnlineStatusEnum;
import com.home.common.framework.core.entity.EntityUtils;
import com.home.common.utils.msg.MessageUtils;
import com.home.common.utils.string.StringUtils;
import com.home.security.browser.auth.entity.SysUser;
import com.home.security.browser.auth.mapper.SysUserMapper;
import com.home.security.browser.auth.mapper.SysUserOnlineMapper;
import com.home.security.browser.manager.AsyncManager;
import com.home.security.browser.manager.factory.AsyncFactory;
import com.home.security.browser.manager.session.SysUserOnline;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * Description: 登录
 * Created by 王大宸 on 2020-10-08 16:07
 * Created with IntelliJ IDEA.
 */
@Service
public class LoginUserService {
    private static final Logger logger = LoggerFactory.getLogger(LoginUserService.class);
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserOnlineMapper sysUserOnlineMapper;

    /***
     * 功能说明：登录验证
     *
     * @author 王大宸
     * @date 2020/10/8 16:31
     * @param username 登录账号
     * @return com.home.security.browser.auth.entity.SysUser
     */
    public SysUser login(String username, String client) {
        if (StringUtils.isEmpty(username)) {
            logger.error("登录账号为空......");
            throw new UnknownAccountException();
        }
        SysUser sysUser = userMapper.getByUsername(username);
        if (null == sysUser) {
            logger.error("登录账号: " + username + ",  找不到登录用户");
            throw new UnknownAccountException();
        }
        if (null == sysUser.getStatus()
                || "2".equals(sysUser.getStatus())
                || "0".equals(sysUser.getStatus())) {
            logger.error("登录账号: " + username + "  已被冻结，冻结状态为: " + sysUser.getStatus());
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, sysUser.getName(), client,
                    Constants.LOGIN_FAIL, MessageUtils.message(I18nMessages.USER_BLOCKED)));
            throw new LockedAccountException();
        }
        // 删除之前的会话,保证一个账号只有一个人在线
        SysUserOnline sysUserOnline = new SysUserOnline();
        sysUserOnline.setLoginName(sysUser.getUsername());
        sysUserOnline.setClientId(client);
        sysUserOnlineMapper.delete(sysUserOnline);

        // 在线用户入库
        SysUserOnline session = new SysUserOnline();
        session.setId(EntityUtils.getId());
        session.setLoginName(username);
        session.setCreateTime(LocalDateTime.now());
        session.setCreateUser(sysUser.getName());
        session.setCreateUserId(sysUser.getId());
        session.setStatus(OnlineStatusEnum.on_line);
        session.setClientId(client);
        AsyncManager.me().execute(AsyncFactory.syncSessionToDb(session));

        // 登录日志
        AsyncManager.me().execute(
                AsyncFactory.recordLogininfor(username,
                        sysUser.getName(),
                        client,
                        Constants.LOGIN_SUCCESS,
                        MessageUtils.message(I18nMessages.USER_LOGIN_SUCCESS)));

        sysUser.setClientId(client);
        return sysUser;
    }


}
